<?
error_reporting(E_ALL ^ E_NOTICE);
$header = "";

// Read the post from PayPal and add 'cmd'
$req = 'cmd=_notify-validate';

if(function_exists('get_magic_quotes_gpc')){
	$get_magic_quotes_exits = true;
}

$this->orderContainer->log($this->orderContainer->id() . " PayPal IPN Listener - Received POST from PayPal for order " . extractStringWithKeyFromArray(PAYPAL_ORDERID_VARIABLE, $_POST, NULL) . " : ");
foreach ($_POST as $key => $value){
// Handle escape characters, which depends on setting of magic quotes
	if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1){
		$value = urlencode(stripslashes($value));
	} else {
		$value = urlencode($value);
	}
	$req .= "&$key=$value";
}

// Post back to PayPal to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
$fp = fsockopen (PAYPAL_LISTENER_URL, 80, $errno, $errstr, 30);
$this->orderContainer->log($this->orderContainer->id() . " PayPal IPN Listener - Preparing to send POST back to PayPal for order " . extractStringWithKeyFromArray(PAYPAL_ORDERID_VARIABLE, $_POST, NULL) . " : ");
// Process validation from PayPal
// TODO: This sample does not test the HTTP response code. All
// HTTP response codes must be handles or you should use an HTTP
// library, such as cUrl

$verified = false;
$invalidResponse = false;
if (!$fp) { // HTTP ERROR
	$this->orderContainer->log($this->orderContainer->id() . " PayPal IPN Listener - Error occurred while establishing connection with PayPal for order " . extractStringWithKeyFromArray(PAYPAL_ORDERID_VARIABLE, $_POST, NULL) . " sending POST" .  $req . " : ");
} else {	
	$this->orderContainer->log($this->orderContainer->id() . " PayPal IPN Listener - Connection established successfully with PayPal for order " . extractStringWithKeyFromArray(PAYPAL_ORDERID_VARIABLE, $_POST, NULL) . " : ");
	// NO HTTP ERROR
	fputs ($fp, $header . $req);
	while (!feof($fp)) {
		$res = fgets ($fp, 1024);

		if (strcmp ($res, "VERIFIED") == 0) {
			$verified = true;
			break;	
		} else if (strcmp ($res, "INVALID") == 0) {
			$this->orderContainer->log(" PayPal IPN Listener - Received INVALID response from PayPal IPN: ");
			$verified = false;
			$invalidResponse = true;
			break;						
		}
	}
}

fclose ($fp);
